package com.zhuhjay.system.config;

import com.zhuhjay.system.filter.AuthTokenFilter;
import com.zhuhjay.system.service.IUserService;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Collections;

/**
 * 用来注册Web的组件(Filter, Servlet, Listener)的配置文件
 * @author ZhuHJay
 * @date 2022/3/20 16:36
 */
@Configuration
public class WebRegistrationBeanConfiguration {

    /** 跨域请求过滤器配置 **/
    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOriginPattern("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);

        FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
        //这里设置优先级最高
        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return bean;
    }

    /** 权限认证的过滤器配置 **/
    @Bean
    public FilterRegistrationBean<AuthTokenFilter> authTokenFilter(IUserService userService){
        FilterRegistrationBean<AuthTokenFilter> authTokenFilter =
                new FilterRegistrationBean<>(new AuthTokenFilter(userService));
        authTokenFilter.setUrlPatterns(Collections.singletonList("/*"));
        return authTokenFilter;
    }

}
